// pages/my/register/register.js
const defaultAvatarUrl = '../../../images/noUser.png'
var api = require('../../../config/api.js');
const https = require('../../../utils/request.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      id: '',
      avatarUrl: defaultAvatarUrl,
      avatar: '',
      name: '',
      iphone: '',
      code: ''
    },
    // canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    // canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },

  // 保存
  async formSubmit(e) {
    let that = this;
    wx.showLoading();
    let formData = e.detail.value;
    console.log('form发生了submit事件，携带数据为：', formData);
    // 验证
    if (that.validateForm(formData)) {
      console.log('头像', logo)
      // 上传头像
      let logo = await that.updateLogo();
      if (logo) {
        // 保存
        let params = {
          id: that.data.userInfo.id,
          avatar: that.data.userInfo.avatar,
          openid: wx.getStorageSync('openid'),
          name: formData.name,
          iphone: formData.iphone,
          code: formData.code
        }
        https.request(api.AuthRegister, params, 'post').then(res => {
          if (res.error_code == 0) {
            // 注册成功
            wx.showToast({
              icon: 'none',
              title: '保存成功',
            })
            // 更新注册信息
            if (params.id) {
              wx.setStorageSync('userInfo', params)
              wx.switchTab({
                url: '/pages/my/my'
              })
            } else {
              wx.navigateBack();
            }
          }
        }).catch(err => {
          wx.hideLoading()
          console.log('错误', err)
        })


      } else {}

    } else {}


  },
  // 上传头像
  updateLogo() {
    let that = this;
    let logo = that.data.userInfo.avatarUrl;
    console.log('待上传头像', that.data.userInfo)
    return new Promise((resolve, reject) => {
      if (logo.indexOf('noUser') != -1) {
        wx.showToast({
          icon: 'none',
          title: '请选择头像',
        })
        reject(false);
      } else if (logo.indexOf('//tmp') == -1) {
        // 未编辑头像
        resolve(true);
      } else {
        // 上传头像
        wx.uploadFile({
          url: api.UserUpload,
          filePath: logo,
          name: 'file',
          formData: {},
          success(res) {
            console.log('头像提交成功', res)
            if (res.statusCode == 200) {
              let resData = JSON.parse(res.data);
              if (resData.error_code == 0) {
                // 上传成功
                that.setData({
                  "userInfo.avatarUrl": resData.data.sbimg,
                  "userInfo.avatar": resData.data.sbimg
                })
                resolve(true);
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '头像上传失败',
                })
                reject(false);
              }
            } else {
              wx.showToast({
                icon: 'none',
                title: '头像上传失败',
              })
              reject(false);
            }
            //do something
          },
          fail: (err) => {
            //上传失败：修改pedding为reject
            console.log('头像上传失败：', err)
            wx.showToast({
              title: "网络出错,上传失败",
              icon: 'none'
            });
            reject(false)
          }
        })

      }

    })

  },
  validateForm(formData) {
    let that = this;
    // let formData = that.data.userInfo;
    let rstMsg = "";
    if (formData.name.length == 0) {
      rstMsg = '昵称不能为空';
    } else if (formData.iphone.length == 0) {
      rstMsg = '手机号不能为空';
    } else if (formData.iphone.length != 11) {
      rstMsg = '手机号格式错误';
    }
    if (rstMsg != '') {
      wx.showToast({
        icon: 'none',
        title: rstMsg,
      })
      return false;
    }
    return true;
  },

  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    this.setData({
      "userInfo.nickName": nickName
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 如果登录过，回显用户信息
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo.id) {
      that.setData({
        'userInfo.id': userInfo.id,
        'userInfo.avatarUrl': userInfo.avatar,
        'userInfo.avatar': userInfo.avatar,
        'userInfo.name': userInfo.name,
        'userInfo.iphone': userInfo.iphone,
        'userInfo.code': userInfo.code
      })

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})